package com.servlet;

import com.dao.BuildDao;
import com.dao.RoomDao;
import com.dao.UserDao;
import com.model.Build;
import com.model.PageBean;
import com.model.Room;
import com.model.User;
import com.util.DbUtil;
import com.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;

/**
 * 宿舍管理
 * @author : wangjg
 * @date : 2023/11/1 16:24
 */
@WebServlet(name = "RoomServlet")
public class RoomServlet extends HttpServlet {

    DbUtil dbUtil = new DbUtil();
    RoomDao roomDao = new RoomDao();
    BuildDao buildDao = new BuildDao();
    UserDao userDao = new UserDao();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        Object currentUserType = session.getAttribute("currentUserType");
        String searchText = request.getParameter("searchText");
        String buildId = request.getParameter("buildId");
        String searchType = request.getParameter("searchType");
        String name = request.getParameter("name");
        String action = request.getParameter("action");
        String page = request.getParameter("page");
        if(StringUtil.isEmpty(page)){
            page = "0";
        }
        Room room = new Room();
        if("preSave".equals(action)) {
            roomPreSave(request, response);
            return;
        } else if("save".equals(action)){
            roomSave(request, response);
            return;
        } else if("preRoomAlloc".equals(action)){
            preRoomAlloc(request, response);
            return;
        }else if("alloc".equals(action)){
            roomAlloc(request, response);
            return;
        } else if("list".equals(action)) {
            if(StringUtil.isNotEmpty(searchText)) {
                if("name".equals(searchType)) {
                    room.setNum(searchText);
                }
            }
            if(StringUtil.isNotEmpty(buildId)) {
                room.setBuildId(Integer.parseInt(buildId));
            }
            session.removeAttribute("searchText");
            session.removeAttribute("searchType");
            session.removeAttribute("buildId");
            request.setAttribute("searchText", searchText);
            request.setAttribute("searchType", searchType);
            request.setAttribute("buildId", buildId);
        } else if("search".equals(action)){
            if(StringUtil.isNotEmpty(name)) {
                room.setNum(name);
                session.setAttribute("searchText", searchText);
                session.setAttribute("searchType", searchType);
                session.setAttribute("name", name);
            } else {
                session.removeAttribute("searchText");
                session.removeAttribute("searchType");
                session.removeAttribute("name");
            }

            if(StringUtil.isNotEmpty(buildId)) {
                room.setBuildId(Integer.parseInt(buildId));
                session.setAttribute("buildId", buildId);
            }else {
                session.removeAttribute("buildId");
            }
        }else{
            if(StringUtil.isEmpty(searchText) && StringUtil.isEmpty(buildId)) {
                Object o1 = session.getAttribute("searchText");
                Object o2 = session.getAttribute("searchType");
                Object o3 = session.getAttribute("buildId");
                if(o1!=null) {
                    if("name".equals(o2)) {
                        room.setNum((String)o1);
                    }
                }
                if(o3 != null) {
                    room.setBuildId(Integer.parseInt((String)o3));
                }
            }
        }
        Connection con = null;
        PageBean pageBean = new PageBean(Integer.parseInt(page), 5);
        request.setAttribute("pageSize", pageBean.getPageSize());
        request.setAttribute("page", pageBean.getPage());
        try {
            con=dbUtil.getCon();
            if("admin".equals(currentUserType)) {
                List<Room> roomList = roomDao.roomList(con, new PageBean(Integer.parseInt(page),5),room);
                List<Build> buildList = buildDao.buildList(con, null, new Build());
                int total = roomDao.roomCount(con, room);
                String pageCode = this.genPage(total, Integer.parseInt(page),5);
                request.setAttribute("pageCode", pageCode);
                request.setAttribute("buildList", buildList);
                request.setAttribute("roomList", roomList);
                request.setAttribute("mainPage", "admin/room.jsp");
                request.getRequestDispatcher("mainAdmin.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void roomSave(HttpServletRequest request,
                            HttpServletResponse response)throws ServletException, IOException {
        String num = request.getParameter("num");
        String buildId = request.getParameter("buildId");
        String capacity = request.getParameter("capacity");
        Connection con = null;
        try {
            con = dbUtil.getCon();
            HttpSession session = request.getSession();
            User admin = (User)(session.getAttribute("currentUser"));
            Build build = buildDao.buildInfo(con, Integer.parseInt(buildId));
            Room room = new Room(Integer.parseInt(buildId),build.getName(),num,capacity,"未满");
            int saveNum = roomDao.addRoom(con,room);
            if(saveNum > 0) {
                request.getRequestDispatcher("room?action=list").forward(request, response);
            } else {
                request.setAttribute("room", room);
                request.setAttribute("error", "保存失败");
                request.setAttribute("mainPage", "admin/roomSave.jsp");
                request.getRequestDispatcher("mainAdmin.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void roomPreSave(HttpServletRequest request,
                               HttpServletResponse response)throws ServletException, IOException {
        Connection con = null;
        try {
            con = dbUtil.getCon();
            String roomId = request.getParameter("roomId");
            if(StringUtil.isNotEmpty(roomId)){
                Room room = roomDao.roomInfo(con, Integer.parseInt(roomId));
                request.setAttribute("room", room);
            }
            List<Build> buildList = buildDao.buildList(con, null, new Build());
            request.setAttribute("buildList", buildList);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        request.setAttribute("mainPage", "admin/roomSave.jsp");
        request.getRequestDispatcher("mainAdmin.jsp").forward(request, response);
    }

    private void preRoomAlloc(HttpServletRequest request,
                           HttpServletResponse response)throws ServletException, IOException {
        Connection con = null;
        try {
            con = dbUtil.getCon();
            HttpSession session = request.getSession();
            List<User> userList = userDao.userList(con, null, new User());
            request.setAttribute("userList", userList);
            request.setAttribute("mainPage", "admin/roomAlloc.jsp");
            request.getRequestDispatcher("mainAdmin.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void roomAlloc(HttpServletRequest request,
                           HttpServletResponse response)throws ServletException, IOException {
        String roomId = request.getParameter("roomId");
        String buildId = request.getParameter("buildId");
        String userId = request.getParameter("userId");
        Connection con = null;
        try {
            con = dbUtil.getCon();
            HttpSession session = request.getSession();
            Room room = roomDao.roomInfo(con, Integer.parseInt(roomId));
            Build build = buildDao.buildInfo(con,Integer.parseInt(buildId));
            User user = userDao.userInfo(con, userId);
            user.setRoomId(Integer.parseInt(roomId));
            user.setBuildId(Integer.parseInt(buildId));
            user.setRoomNum(room.getNum());
            user.setBuildName(build.getName());
            int updateNum = userDao.updateUser(con,user);
            if(updateNum > 0) {
                request.getRequestDispatcher("room?action=list").forward(request, response);
            } else {
                request.setAttribute("room", room);
                request.setAttribute("error", "分配失败");
                request.setAttribute("mainPage", "admin/roomSave.jsp");
                request.getRequestDispatcher("mainAdmin.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private String genPage(int totalNum, int currentPage, int pageSize){
        int totalPage = totalNum%pageSize==0?totalNum/pageSize:totalNum/pageSize+1;
        StringBuilder pageCode = new StringBuilder();
        pageCode.append("<li><a href='room?page=1'>首页</a></li>");
        if(currentPage==1) {
            pageCode.append("<li class='disabled'><a href='#'>上一页</a></li>");
        }else {
            pageCode.append("<li><a href='room?page=").append(currentPage - 1).append("'>上一页</a></li>");
        }
        for(int i=currentPage-2;i<=currentPage+2;i++) {
            if(i<1||i>totalPage) {
                continue;
            }
            if(i==currentPage) {
                pageCode.append("<li class='active'><a href='#'>").append(i).append("</a></li>");
            } else {
                pageCode.append("<li><a href='room?page=").append(i).append("'>").append(i).append("</a></li>");
            }
        }
        if(currentPage==totalPage) {
            pageCode.append("<li class='disabled'><a href='#'>下一页</a></li>");
        } else {
            pageCode.append("<li><a href='room?page=").append(currentPage + 1).append("'>下一页</a></li>");
        }
        pageCode.append("<li><a href='room?page=").append(totalPage).append("'>尾页</a></li>");
        return pageCode.toString();
    }
}
